package com.tz.cartelo.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.tz.cartelo.BaseApplication;
import com.tz.cartelo.R;
import com.tz.cartelo.constant.Api;
import com.tz.cartelo.constant.Key;
import com.tz.cartelo.model.DataParams;
import com.tz.cartelo.model.GoodsPictureHead;
import com.tz.cartelo.model.GoodsSubclass;
import com.tz.cartelo.result.ResultGoodsDetails;
import com.tz.cartelo.util.AES;
import com.tz.cartelo.util.CommonUtils;
import com.tz.cartelo.view.GlideImageLoader;
import com.tz.common.util.LogUtil;
import com.tz.common.util.PreferencesUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * Created by Administrator on 2017/4/16.
 */

public class GoodsDetailsActivity extends DataLoadActivity implements View.OnClickListener, BGARefreshLayout.BGARefreshLayoutDelegate {
    private static final String TAG = "GoodsDetailsActivity";
    private static final int EDIT_ORDER = 1;
    private BGARefreshLayout mRefreshLayout;
    private Api mApi;
    //    private GoodsDetailsAdapter mGoodsDetailsAdapter;
    private TextView mGoodsDetailsGoodsName, mGoodsDetailsGoodsPrice, mGoodsDetailsGoodsNew, mGoodsDetailsGoodsSale, mGoodsDetailsGoodsStock, textView;
    private LinearLayout mGoodsDetailsGoodsStyleLayout;
    private RelativeLayout mGoodsDetailsVideoLayout;
    private List<GoodsSubclass> mGoodsSubclassList;
    private Banner mGoodsDetailsBanner;
    private VideoView mGoodsDetailsVideo;
    private ImageView mGoodsDetailsVideoImg;
    private WebView mWebView;
    //    private ListView goodsDetailsList;
//    private View headerView;
    private boolean mIsActivityResult;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_goods_details;
    }

    @Override
    protected void init() {
        BaseApplication.addActivity(this);

//        mRefreshLayout = (BGARefreshLayout) findViewById(R.id.fresh_layout);
//        mRefreshLayout.setDelegate(this);
//        CommonUtils.setBGARefreshLayout(mRefreshLayout, this);

        findViewById(R.id.goods_details_center_layout).setOnClickListener(this);
        findViewById(R.id.goods_details_edit_layout).setOnClickListener(this);
        TextView goods_details_edit_text = (TextView) findViewById(R.id.goods_details_edit_text);
//        goodsDetailsList = (ListView) findViewById(R.id.goods_details_list);
//        headerView = LayoutInflater.from(this).inflate(R.layout.item_goods_details_head, null);
//        goodsDetailsList.addHeaderView(headerView);
//        mGoodsPictureTailList = new ArrayList<>();
//        mGoodsDetailsAdapter = new GoodsDetailsAdapter(this, mGoodsPictureTailList);
//        goodsDetailsList.setAdapter(mGoodsDetailsAdapter);

        mGoodsDetailsBanner = (Banner) findViewById(R.id.goods_details_banner);
        mGoodsDetailsBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mGoodsDetailsBanner.isAutoPlay(true);
        mGoodsDetailsBanner.setDelayTime(Key.BANNER_TIME);
        mGoodsDetailsBanner.setImageLoader(new GlideImageLoader());

        int imgWidth = CommonUtils.getScreenWidth(this);
        int imgHeight = imgWidth;
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(imgWidth, imgHeight);
        mGoodsDetailsBanner.setLayoutParams(layoutParams);

        mGoodsDetailsGoodsName = (TextView) findViewById(R.id.goods_details_goods_name);
        mGoodsDetailsGoodsPrice = (TextView) findViewById(R.id.goods_details_goods_price);

        mGoodsDetailsGoodsNew = (TextView) findViewById(R.id.goods_details_goods_is_new);
        mGoodsDetailsGoodsSale = (TextView) findViewById(R.id.goods_details_goods_sale);
        mGoodsDetailsGoodsStock = (TextView) findViewById(R.id.goods_details_goods_stock);
        LinearLayout goodsDetailsStockLayout = (LinearLayout) findViewById(R.id.goods_details_stock_layout);
        LinearLayout stockDetailsStockLayout = (LinearLayout) findViewById(R.id.stock_details_stock_layout);

        mGoodsDetailsVideoLayout = (RelativeLayout) findViewById(R.id.goods_details_video_layout);
        mGoodsDetailsVideoImg = (ImageView) findViewById(R.id.goods_details_image);
        mGoodsDetailsVideoImg.setOnClickListener(this);
        mGoodsDetailsVideo = (VideoView) findViewById(R.id.goods_details_video);
        mGoodsDetailsVideo.setMediaController(new MediaController(this));
        mGoodsDetailsGoodsStyleLayout = (LinearLayout) findViewById(R.id.goods_details_goods_style_layout);
        textView = (TextView) findViewById(R.id.textView);

        mWebView = (WebView) findViewById(R.id.goods_details_goods_describe_web);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
//        mWebView.setWebChromeClient(webChromeClient);
//        mWebView.setWebViewClient(webViewClient);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setBlockNetworkImage(false);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(mWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }

        mGoodsSubclassList = new ArrayList<>();
        if (getIntent().getFlags() == Key.CLASSIFY_GOODS) {
            mApi = Api.GOODS_DETAIL;
            goodsDetailsStockLayout.setVisibility(View.VISIBLE);
            stockDetailsStockLayout.setVisibility(View.GONE);
        } else {
            goodsDetailsStockLayout.setVisibility(View.GONE);
            stockDetailsStockLayout.setVisibility(View.VISIBLE);
            mApi = Api.STOCK_MANAGER_DETAILS;
            goods_details_edit_text.setText("编辑库存");
        }
        loadData(mApi, true);
    }

    @Override
    protected void initTitle() {
        ImageView titleBack = (ImageView) findViewById(R.id.title_back);
        titleBack.setVisibility(View.VISIBLE);
        titleBack.setOnClickListener(this);

        TextView titleText = (TextView) findViewById(R.id.title_text);
        if (getIntent().getFlags() == Key.CLASSIFY_GOODS)
            titleText.setText(R.string.goods_details_title);
        else
            titleText.setText(R.string.stock_details_title);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.goods_details_center_layout:
                BaseApplication.clearActivity();
                switchActivityAndFinish(MainActivity.class, null);
                break;
            case R.id.goods_details_edit_layout:
                Bundle bundle = new Bundle();
                bundle.putString(Key.GOODS_ID, getIntent().getStringExtra(Key.GOODS_ID));
                bundle.putSerializable(Key.GOODS_STYLE, (Serializable) mGoodsSubclassList);
                switchActivityForResult(EditOrderActivity.class, EDIT_ORDER, bundle, getIntent().getFlags());
                break;
            case R.id.goods_details_image:
                mGoodsDetailsVideoImg.setVisibility(View.GONE);
                mGoodsDetailsVideo.start();
                break;
            default:
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EDIT_ORDER:
                    mIsActivityResult = true;
                    if (getIntent().getFlags() == Key.CLASSIFY_GOODS)
                        mApi = Api.GOODS_DETAIL;
                    else {
                        mApi = Api.STOCK_MANAGER_DETAILS;
                    }
                    loadData(mApi, true);
//                    Message message = new Message();
//                    Bundle bundle=new Bundle();
//                    bundle.putInt("plusmoney",plusMoney);
//                    bundle.putString("mdate", jsonObject.getJSONObject("apiData").getString("time"));
//                    message.setData(bundle);
//                    bidHandler.sendMessage(message);
                    break;
                default:
                    break;
            }
        }
    }

//    private Handler bidHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            Bundle bundle=msg.getData();
//            String mDate=bundle.getString("mdate");
//            Integer plusMoney=bundle.getInt("plusmoney");
//            if (getIntent().getFlags() == Key.CLASSIFY_GOODS)
//                mApi = Api.GOODS_DETAIL;
//            else {
//                mApi = Api.STOCK_MANAGER_DETAILS;
//            }
//            loadData(mApi, true);
//        }
//    };

    @Override
    protected void initParams(DataParams params) {
        switch (mApi) {
            case GOODS_DETAIL:
                params.addParam("goodsId", getIntent().getStringExtra(Key.GOODS_ID));
                break;
            case STOCK_MANAGER_DETAILS:
                params.addParam("userId", PreferencesUtils.getString(Key.PER_USER_ID, ""));
                params.addParam("goodsId", getIntent().getStringExtra(Key.GOODS_ID));
                String time = System.currentTimeMillis() + "";
                params.addParam("time", time);
                List<String> dataList = new ArrayList<>();
                dataList.add(PreferencesUtils.getString(Key.PER_USER_ID, ""));
                dataList.add(getIntent().getStringExtra(Key.GOODS_ID));
                dataList.add(time);
                try {
                    params.addParam("sign", AES.createASE(dataList));
                } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void disposeResult(Api api, String response) {
        LogUtil.d(TAG, response);
        switch (api) {
            case GOODS_DETAIL:
            case STOCK_MANAGER_DETAILS:
                //结束刷新和加载
//                mRefreshLayout.endRefreshing();
//                mRefreshLayout.endLoadingMore();

                ResultGoodsDetails resultGoodsDetails = fromJson(response, ResultGoodsDetails.class);
                if (!resultGoodsDetails.isSuccess()) {
                    showToast(resultGoodsDetails.getMessage());
                    return;
                }
                if (mIsActivityResult) {//TODO 编辑订单后修改库存v

                    if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                        mGoodsDetailsGoodsSale.setText("我的销量" + resultGoodsDetails.getGoodsDetails().getSalesNum() + getString(R.string.goods_details_month_sale_unit));
                        mGoodsDetailsGoodsStock.setText("我的库存" + resultGoodsDetails.getGoodsDetails().getTotalNum());
                    } else {
                        mGoodsDetailsGoodsSale.setText(getString(R.string.goods_details_month_sale) + resultGoodsDetails.getGoodsDetails().getSalesNum() + getString(R.string.goods_details_month_sale_unit));
                        mGoodsDetailsGoodsStock.setText(getString(R.string.goods_details_total_stock) + resultGoodsDetails.getGoodsDetails().getTotalNum());
                    }

                    mGoodsSubclassList.clear();
                    mGoodsSubclassList.addAll(resultGoodsDetails.getGoodsDetails().getGoodsSubclassList());

                    List<GoodsSubclass> goodsSubclassList = new ArrayList<>();
                    goodsSubclassList.addAll(resultGoodsDetails.getGoodsDetails().getGoodsSubclassList());
                    mGoodsDetailsGoodsStyleLayout.removeAllViews();
                    int groupType = 1;
                    for (GoodsSubclass goodsSubclass : goodsSubclassList) {
                        View goodsStyleView;
                        if (getIntent().getFlags() == Key.CLASSIFY_GOODS) {
                            goodsStyleView = LayoutInflater.from(this).inflate(R.layout.item_goods_style, null);
                        } else {
                            goodsStyleView = LayoutInflater.from(this).inflate(R.layout.item_socket_style, null);
                        }
                        TextView goodsStyleDescribe = (TextView) goodsStyleView.findViewById(R.id.goods_style_describe);
                        TextView goodsStyleStock = (TextView) goodsStyleView.findViewById(R.id.goods_style_stock);
                        TextView goodsStyleSale = (TextView) goodsStyleView.findViewById(R.id.goods_style_sale);
                        goodsStyleDescribe.setText(goodsSubclass.getAppearance());
                        goodsStyleStock.setText(goodsSubclass.getTotalNum());
                        if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                            goodsStyleSale.setVisibility(View.VISIBLE);
                            goodsStyleSale.setText(goodsSubclass.getSalesNum());
                        }

                        if (goodsSubclass.getTotalNum().equals("0")) {
                            goodsStyleDescribe.setTextColor(getResources().getColor(R.color.gray));
                            goodsStyleStock.setTextColor(getResources().getColor(R.color.gray));
                            goodsStyleSale.setTextColor(getResources().getColor(R.color.gray));
                        }

                        if (groupType != Integer.parseInt(goodsSubclass.getGroupType())) {
                            View grayLineView = LayoutInflater.from(this).inflate(R.layout.item_gray_line, null);
                            mGoodsDetailsGoodsStyleLayout.addView(grayLineView);
                            groupType++;
                        }
                        mGoodsDetailsGoodsStyleLayout.addView(goodsStyleView);
                    }
                    mIsActivityResult = false;
                } else {
                    if (resultGoodsDetails.getGoodsDetails().getGoodsPictureTailList() != null && resultGoodsDetails.getGoodsDetails().getGoodsPictureTailList().size() > 0)
                        mWebView.loadDataWithBaseURL(null, resultGoodsDetails.getGoodsDetails().getGoodsPictureTailList().get(0).getRemark(), "text/html", "UTF-8", null);
                    else
                        textView.setVisibility(View.GONE);

                    if (null == resultGoodsDetails.getGoodsDetails().getGoodsVideoList() || resultGoodsDetails.getGoodsDetails().getGoodsVideoList().isEmpty()) {
                        mGoodsDetailsVideoLayout.setVisibility(View.GONE);
                    } else {
                        mGoodsDetailsVideoLayout.setVisibility(View.VISIBLE);
                        ImageLoader.getInstance().displayImage(resultGoodsDetails.getGoodsDetails().getGoodsVideoList().get(0).getPictureUrl(), mGoodsDetailsVideoImg, CommonUtils.optionsList());
                        mGoodsDetailsVideo.setVideoPath(resultGoodsDetails.getGoodsDetails().getGoodsVideoList().get(0).getVideoUrl());
                    }

                    List<String> mImgUrlList = new ArrayList<>();
                    for (GoodsPictureHead goodsPictureHead : resultGoodsDetails.getGoodsDetails().getGoodsPictureHeadList()) {
                        mImgUrlList.add(goodsPictureHead.getPictureUrl());
                    }
                    mGoodsDetailsBanner.setImages(mImgUrlList);
                    mGoodsDetailsBanner.start();

                    mGoodsDetailsGoodsName.setText(resultGoodsDetails.getGoodsDetails().getTitle());
                    mGoodsDetailsGoodsPrice.setText("¥ " + resultGoodsDetails.getGoodsDetails().getPrice());
                    if (CommonUtils.isEmpty(resultGoodsDetails.getGoodsDetails().getVariety())) {
                        mGoodsDetailsGoodsNew.setVisibility(View.GONE);
                    } else {
                        mGoodsDetailsGoodsNew.setText(resultGoodsDetails.getGoodsDetails().getVariety());
                    }

                    if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                        mGoodsDetailsGoodsSale.setText("我的销量" + resultGoodsDetails.getGoodsDetails().getSalesNum() + getString(R.string.goods_details_month_sale_unit));
                        mGoodsDetailsGoodsStock.setText("我的库存" + resultGoodsDetails.getGoodsDetails().getTotalNum());
                    } else {
                        mGoodsDetailsGoodsSale.setText(getString(R.string.goods_details_month_sale) + resultGoodsDetails.getGoodsDetails().getSalesNum() + getString(R.string.goods_details_month_sale_unit));
                        mGoodsDetailsGoodsStock.setText(getString(R.string.goods_details_total_stock) + resultGoodsDetails.getGoodsDetails().getTotalNum());
                    }


                    mGoodsSubclassList.addAll(resultGoodsDetails.getGoodsDetails().getGoodsSubclassList());
                    int groupType = 1;
                    for (GoodsSubclass goodsSubclass : mGoodsSubclassList) {
                        View goodsStyleView;
                        if (getIntent().getFlags() == Key.CLASSIFY_GOODS) {
                            goodsStyleView = LayoutInflater.from(this).inflate(R.layout.item_goods_style, null);
                        } else {
                            goodsStyleView = LayoutInflater.from(this).inflate(R.layout.item_socket_style, null);
                        }
                        TextView goodsStyleDescribe = (TextView) goodsStyleView.findViewById(R.id.goods_style_describe);
                        TextView goodsStyleStock = (TextView) goodsStyleView.findViewById(R.id.goods_style_stock);
                        TextView goodsStyleSale = (TextView) goodsStyleView.findViewById(R.id.goods_style_sale);
                        goodsStyleDescribe.setText(goodsSubclass.getAppearance());
                        goodsStyleStock.setText(goodsSubclass.getTotalNum());

                        if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                            goodsStyleSale.setVisibility(View.VISIBLE);
                            goodsStyleSale.setText(goodsSubclass.getSalesNum());
                        }

                        if (goodsSubclass.getTotalNum().equals("0")) {
                            goodsStyleDescribe.setTextColor(getResources().getColor(R.color.gray));
                            goodsStyleStock.setTextColor(getResources().getColor(R.color.gray));
                            goodsStyleSale.setTextColor(getResources().getColor(R.color.gray));
                        }

                        if (groupType != Integer.parseInt(goodsSubclass.getGroupType())) {
                            View grayLineView = LayoutInflater.from(this).inflate(R.layout.item_gray_line, null);
                            mGoodsDetailsGoodsStyleLayout.addView(grayLineView);
                            groupType++;
                        }
                        mGoodsDetailsGoodsStyleLayout.addView(goodsStyleView);
                    }
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
//        mIsActivityResult = true;
//        if (getIntent().getFlags() == Key.CLASSIFY_GOODS)
//            mApi = Api.GOODS_DETAIL;
//        else {
//            mApi = Api.STOCK_MANAGER_DETAILS;
//        }
//        loadData(mApi, true);
        mRefreshLayout.endRefreshing();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        mRefreshLayout.endLoadingMore();
        return false;
    }

    @Override
    protected void onPause() {
        mWebView.reload();
        super.onPause();
    }
}
